<template>
  <div>
    <!-- <div style="margin:20px 0 0 40px;color:red;">设置规则：年>半年>季>月</div> -->
    <code style="width:800px;margin-left:20px;margin-top:10px;">
      <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>设置规则：年 > 半年 > 季 > 月（会员价格必须大于0）
    </code>
    <el-form class="form-container" :model="postForm" v-loading="formLoading" ref="postForm">
      <div>
        <table style="width: 700px;padding: 20px 0 20px 30px;">
          <tr style="font-size: 14px;">
            <th>类型</th>
            <th>收费类型</th>
            <th>赠方案包个数</th>
            <th>是否启用</th>
          </tr>
          <tr>
            <td colspan="4">
              <hr />
            </td>
          </tr>
          <template v-for="(item, index) in postForm.vipOpenUse">
            <tr v-if="index == 4">
              <td colspan="4">
                <hr />
              </td>
            </tr>
            <tr>
              <td v-if="index == 0 || index == 4" rowspan="4">
                {{item.vipType == 2 ? 'VIP' : (item.vipType == 4 ? 'SVIP'
                : '')}}
              </td>
              <td>
                <el-input
                  type="number"
                  min="0"
                  style="width: 100px;"
                  v-model="postForm.vipOpenUse[index].price"
                ></el-input>
                <span class="width60">
                  元/
                  <span v-if="item.duration == 12">年</span>
                  <span v-if="item.duration == 6">半年</span>
                  <span v-if="item.duration == 3">季度</span>
                  <span v-if="item.duration == 1">月</span>
                </span>
              </td>
              <td>
                <el-input type="number" v-model="item.points" style="width:70px"></el-input>个
              </td>
              <td>
                <el-checkbox
                  v-if="Number(postForm.vipOpenUse[index].price) > 0"
                  v-model="postForm.vipOpenUse[index].status"
                >启用</el-checkbox>
                <el-checkbox
                  v-if="!postForm.vipOpenUse[index].price || Number(postForm.vipOpenUse[index].price) == 0"
                  disabled
                  v-model="postForm.vipOpenUse[index].status=false"
                >启用</el-checkbox>
              </td>
            </tr>
          </template>
          <tr>
            <td colspan="4">
              <hr />
            </td>
          </tr>
        </table>
      </div>
      <!-- <h4>VIP权益编辑</h4>
      <code style="width:800px;margin-left:60px;">
        <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>
        备注：每个权益最多支持40个字（先输入内容，再启用）
      </code>
      <div class="borderBottom">
        <span v-show="false">{{line1Index=1}}</span>
        <div class="label-div" v-for="(item, index) in postForm.vipEquity" v-if="item.vipType == 2">
          <label>权益{{line1Index++}}:</label>
          <el-input :maxlength=40 v-model="postForm.vipEquity[index].description" placeholder="请输入内容"
                    style="width: 240px;margin-right:30px"></el-input>
          <el-checkbox v-if="postForm.vipEquity[index].description" v-model="postForm.vipEquity[index].status">是否开启
          </el-checkbox>
          <el-checkbox v-else v-model="postForm.vipEquity[index].status = false" disabled>是否开启</el-checkbox>
          <label>排序:</label>
          <el-input type="number" min="0" v-model="postForm.vipEquity[index].sort" style="width: 100px"></el-input>
          <span @click="removeEle(index)" v-if="line1Index != 2" style="margin-left:30px;cursor:pointer;color: red;"
                tiele="点击删除">✘</span>
        </div>
        <el-button class="c-mb10" type="primary" style="margin-left:300px;" @click="addVip(2, line1Index)">添加
        </el-button>
      </div>
      <h4>SVIP权益编辑</h4>
      <code style="width:800px;margin-left:60px;">
        <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>
        备注：每个权益最多支持40个字（先输入内容，再启用）
      </code>
      <div class="borderBottom">
        <span v-show="false">{{line2Index=1}}</span>
        <div class="label-div" v-for="(item, index) in postForm.vipEquity" v-if="item.vipType == 4">
          <label>权益{{line2Index++}}:</label>
          <el-input :maxlength=40 v-model="postForm.vipEquity[index].description" placeholder="请输入内容"
                    style="width: 240px;margin-right:30px"></el-input>
          <el-checkbox v-if="postForm.vipEquity[index].description" v-model="postForm.vipEquity[index].status">是否开启
          </el-checkbox>
          <el-checkbox v-else v-model="postForm.vipEquity[index].status = false" disabled>是否开启</el-checkbox>
          <label>排序:</label>
          <el-input type="number" min="0" v-model="postForm.vipEquity[index].sort" style="width: 100px"></el-input>
          <span @click="removeEle(index)" v-if="line2Index != 2" style="margin-left:30px;cursor:pointer;color: red;"
                tiele="点击删除">✘</span>
        </div>
        <el-button class="c-mb10" type="primary" style="margin-left:300px;" @click="addVip(4, line2Index)">添加
        </el-button>
      </div>-->
      <el-form-item v-if="permission == 3" style="padding: 10px 0;width:500px;text-align:center;">
        <el-button type="primary" v-loading="btnLoading" icon="el-icon-check" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
    <div class="clearfix">
      <el-upload
        :action="imageUploadUrl"
        list-type="picture-card"
        name="avatar"
        :file-list="postForm.banner"
        :limit="1"
        :before-upload="handleBeforeUpload"
        :on-success="handleBannerSuccess"
        :on-remove="handleRemove"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <div class="el-upload__tip" slot="tip">只能上传图片文件，且不超过3MB（第一张作为缩略图）</div>
    </div>
  </div>
</template>
<script>
import { getVipBene, vipBeneSave } from "@/api/member";
import { marketing_member_vipBenefit } from "@/utils/permission";
const postForm = {
  vipOpenUse: [
    {
      cmpId: null,
      companyId: null,
      vipType: 2,
      duration: 12,
      price: null,
      status: 1
    },
    {
      cmpId: null,
      companyId: null,
      vipType: 2,
      duration: 6,
      price: null,
      status: 1
    },
    {
      cmpId: null,
      companyId: null,
      vipType: 2,
      duration: 3,
      price: null,
      status: 1
    },
    {
      cmpId: null,
      companyId: null,
      vipType: 2,
      duration: 1,
      price: null,
      status: 1
    },
    {
      cmpId: null,
      companyId: null,
      vipType: 4,
      duration: 12,
      price: null,
      status: 1
    },
    {
      cmpId: null,
      companyId: null,
      vipType: 4,
      duration: 6,
      price: null,
      status: 1
    },
    {
      cmpId: null,
      companyId: null,
      vipType: 4,
      duration: 3,
      price: null,
      status: 1
    },
    {
      cmpId: null,
      companyId: null,
      vipType: 4,
      duration: 1,
      price: null,
      status: 1
    }
  ],
  vipEquity: [
    {
      veId: null,
      companyId: null,
      description: null,
      status: -1,
      vipType: 2,
      sort: null
    },
    {
      veId: null,
      companyId: null,
      description: null,
      status: -1,
      vipType: 4,
      sort: null
    }
  ]
};
export default {
  data() {
    return {
      permission: 3,
      postForm: Object.assign({}, postForm),
      formLoading: false,
      btnLoading: false,
      imageUploadUrl: process.env.BASE_API + "/common/course/imageUpload",
      companies: [{ picture: "" }, { paytPicture: "" }]
    };
  },
  created() {
    this.getModelPermission();
    this.getVipBene();
  },
  methods: {
    handleBeforeUpload(file) {
      console.log("上传文件之前触发啊、。。。");
      const isImg = file.type == "image/jpeg" || file.type == "image/png";
      if (!isImg) {
        this.$message.warning("上传图片只能是 JPG 或 PNG 格式");
      }
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 3MB!");
      }
      return isImg && isLt3M;
    },
    handleBannerSuccess(response, file, fileList) {
      if (response.statusCode == 200) {
        this.postForm.banner.push({
          cbId: null,
          courseId: null,
          url: response.data.imageUrl,
          sort: null
        });
      } else {
        this.$message.error("上传失败，请稍候再试!");
      }
    },
    handleRemove(file, fileList) {
      this.postForm.banner.splice(this.postForm.banner.indexOf(file), 1);
      var data = { imgUrl: file.url };
      delImg(data)
        .then(res => {
          // console.log(res)
        })
        .catch(err => {
          console.log(err);
        });
    },
    getModelPermission() {
      this.permission = marketing_member_vipBenefit();
    },
    getVipBene() {
      getVipBene()
        .then(res => {
          this.postForm.vipOpenUse =
            res.data.data.companyMemberPrice.length == 0
              ? this.postForm.vipOpenUse
              : res.data.data.companyMemberPrice;
          this.postForm.vipOpenUse.forEach((element, index) => {
            this.postForm.vipOpenUse[index].status =
              element.status == 1 ? true : false;
          });

          if (res.data.data.companyMemberPrice.length == 2) {
            this.postForm.vipOpenUse = [
              {
                cmpId: res.data.data.companyMemberPrice[0].cmpId,
                companyId: null,
                vipType: 2,
                duration: 12,
                price: res.data.data.companyMemberPrice[0].price,
                status:
                  res.data.data.companyMemberPrice[0].status == 1 ? true : false
              },
              {
                cmpId: null,
                companyId: null,
                vipType: 2,
                duration: 6,
                price: null,
                status: true
              },
              {
                cmpId: null,
                companyId: null,
                vipType: 2,
                duration: 3,
                price: null,
                status: true
              },
              {
                cmpId: null,
                companyId: null,
                vipType: 2,
                duration: 1,
                price: null,
                status: true
              },
              {
                cmpId: res.data.data.companyMemberPrice[1].cmpId,
                companyId: null,
                vipType: 4,
                duration: 12,
                price: res.data.data.companyMemberPrice[1].price,
                status:
                  res.data.data.companyMemberPrice[1].status == 1 ? true : false
              },
              {
                cmpId: null,
                companyId: null,
                vipType: 4,
                duration: 6,
                price: null,
                status: true
              },
              {
                cmpId: null,
                companyId: null,
                vipType: 4,
                duration: 3,
                price: null,
                status: true
              },
              {
                cmpId: null,
                companyId: null,
                vipType: 4,
                duration: 1,
                price: null,
                status: true
              }
            ];
          }

          this.postForm.vipEquity =
            res.data.data.vipEquity.length == 0
              ? this.postForm.vipEquity
              : res.data.data.vipEquity;
          this.postForm.vipEquity.forEach((element, index) => {
            this.postForm.vipEquity[index].status =
              element.status == 1 ? true : false;
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    addVip(type, lineIndex) {
      console.log(lineIndex);
      if (lineIndex > 5) {
        this.$message({
          type: "warning",
          message: "最多添加5条！"
        });
        return false;
      }
      this.postForm.vipEquity.push({
        veId: null,
        companyId: null,
        description: null,
        status: true,
        vipType: type,
        sort: null
      });
    },
    removeEle(index) {
      this.postForm.vipEquity.splice(index, 1);
    },
    submitForm() {
      // 判断是否开启了vip
      let isOpenVIP =
        this.postForm.vipOpenUse.filter(item => {
          return item.vipType == 2 && item.status;
        }).length > 0
          ? true
          : false;
      // 判断是否开启了svip
      let isOpenSVIP =
        this.postForm.vipOpenUse.filter(item => {
          return item.vipType == 4 && item.status;
        }).length > 0
          ? true
          : false;

      if (!isOpenVIP) {
        this.$message({
          type: "warning",
          message: "至少启用一个vip"
        });
        return;
      }

      // let openVipEquity = false;
      // let openSVipEquity = false;

      // if (isOpenVIP) {
      //   // 开启vip的情况，判断vip权益是否开启和内容是否为空
      //   openVipEquity = this.postForm.vipEquity.filter((item) => {
      //     return item.vipType == 2 && item.status && item.description
      //   }).length > 0 ? true : false;
      // }
      // if (isOpenSVIP) {
      //   // 开启svip的情况，判断vip权益是否开启和内容是否为空
      //   openSVipEquity = this.postForm.vipEquity.filter((item) => {
      //     return item.vipType == 4 && item.status && item.description
      //   }).length > 0 ? true : false;
      // }

      // if (isOpenVIP && !openVipEquity) {
      //   this.$message({
      //     type: 'warning',
      //     message: 'vip权益至少启用一个'
      //   })
      //   return
      // }

      // if (isOpenSVIP && !openSVipEquity) {
      //   this.$message({
      //     type: 'warning',
      //     message: 'svip权益至少启用一个'
      //   })
      //   return
      // }

      var vate = true;
      let maxPrice = 0;
      console.log(this.postForm.vipOpenUse);
      this.postForm.vipOpenUse.forEach((element, index) => {
        // 判断当前价格是否大于前面选中的最大价格
        if (
          index < 3 &&
          this.postForm.vipOpenUse[index].status &&
          this.postForm.vipOpenUse[index].price * 1 <= maxPrice
        ) {
          vate = false;
          return;
        } else if (
          index > 3 &&
          index < 7 &&
          this.postForm.vipOpenUse[index].status &&
          this.postForm.vipOpenUse[index].price * 1 <= maxPrice
        ) {
          vate = false;
          return;
        }

        // 当前选中为最大价格
        if (this.postForm.vipOpenUse[index].status) {
          maxPrice = this.postForm.vipOpenUse[index].price * 1;
        }
        // 到svip把最大价格至0
        if (index == 3) {
          maxPrice = 0;
        }
        // svip的价格要大于vip的价格
        if (index > 3) {
          for (let i = 0; i <= index - 4; i++) {
            if (
              this.postForm.vipOpenUse[index].status &&
              this.postForm.vipOpenUse[i].status &&
              this.postForm.vipOpenUse[index].price * 1 <=
                this.postForm.vipOpenUse[i].price * 1
            ) {
              vate = false;
              return;
            }
          }
        }

        if (
          index > 3 &&
          this.postForm.vipOpenUse[index].status &&
          this.postForm.vipOpenUse[index - 4].status &&
          this.postForm.vipOpenUse[index].price * 1 <=
            this.postForm.vipOpenUse[index - 4].price * 1
        ) {
          vate = false;
          return;
        }
      });
      if (!vate) {
        this.$message({
          type: "warning",
          message: "vip/svip价格设置不合理！"
        });
        return;
      }
      if (this.btnLoading) {
        return;
      }
      this.btnLoading = true;
      console.log(this.postForm);
      var data = { data: this.postForm };
      this.formLoading = true;
      vipBeneSave(data)
        .then(res => {
          this.formLoading = false;
          this.btnLoading = false;
          this.getVipBene();
          this.$message({
            type: "success",
            message: "保存成功！"
          });
        })
        .catch(err => {
          this.formLoading = false;
          this.btnLoading = false;
          console.log(err);
        });
    }
  }
};
</script>
<style scoped>
h4 {
  border-bottom: 1px solid #eee;
  padding-bottom: 20px;
  padding-left: 150px;
  font-size: 14px;
}

.borderBottom {
  border-bottom: 1px solid #eee;
}

label {
  font-size: 12px;
}

.label-div {
  line-height: 50px;
}

.label-div label {
  width: 100px;
  text-align: right;
  display: inline-block;
  margin-right: 30px;
}

table td {
  text-align: center;
}

tr {
  line-height: 40px;
}

.width60 {
  width: 60px;
  display: inline-block;
  text-align: left;
}
</style>
